package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.pojo.DeviceData;
import com.zzyl.nursing.domain.pojo.Room;
import com.zzyl.nursing.domain.vo.BedVo;
import com.zzyl.nursing.domain.vo.DeviceInfo;
import com.zzyl.nursing.domain.vo.RoomVo;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 根据房间Id查询房间数据(楼层、房间、价格)
     *
     * @param id
     */
    @Override
    public RoomVo getRoomInfo(Integer id) {
        return roomMapper.selectRoomVoById(id);
    }

    /**
     * 获取房间中的智能设备及数据
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        //1.查询所有房间(带有设备或者房里的床上的设备)
        List<RoomVo> roomVoList = this.getBaseMapper().getRoomsWithDeviceByFloorId(floorId);
        if (CollectionUtil.isEmpty(roomVoList)) {
            return List.of();  //List.of()表示空集合
        }

        //2.找到每一个设备数据
        //从redis缓存中拿到整体的设备数据,遍历每一份设备数据的小Key当做新map集合的key,每一份设备数据的json字符串value转化为新的Value集合
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollectionUtil.isEmpty(entries)) {
            return roomVoList;
        }
        Map<String, List<DeviceData>> deviceDateMap = entries.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey().toString(), entry -> JSONUtil.toList(entry.getValue().toString(), DeviceData.class)));

        //3.遍历所有房间,和设备、设备数据匹配
        roomVoList.forEach(roomVo -> {
            //3.1遍历查询房间的每一个设备,并填充数据
            List<DeviceInfo> roomDeviceVo = roomVo.getDeviceVos();
            if (CollectionUtil.isNotEmpty(roomDeviceVo)) {
                roomDeviceVo.forEach(deviceVo -> deviceVo.setDeviceDataVos(deviceDateMap.getOrDefault(deviceVo.getIotId(), List.of())));
            }
            //3.2遍历查询房间的每一个床,给设备并填充数据
            List<BedVo> bedVoList = roomVo.getBedVoList();
            if (CollectionUtil.isNotEmpty(bedVoList)) {
                bedVoList.forEach(bedVo -> {
                    List<DeviceInfo> bedDeviceVo = bedVo.getDeviceVos();
                    if (CollectionUtil.isNotEmpty(bedDeviceVo)) {
                        bedDeviceVo.forEach(deviceVo -> deviceVo.setDeviceDataVos(deviceDateMap.getOrDefault(deviceVo.getIotId(), List.of())));
                    }
                });
            }
        });
        return roomVoList;
    }
}
